# -*- coding: utf-8 -*-

import logging
import os

from onlinebrary.lib.base import *

import thread
from pylons import g

log = logging.getLogger(__name__)

class AggregatorController(BaseController):

    def __init__(self):
        pass
    
    def process(self, query):
        data_basket_lock = thread.allocate_lock()
        data_basket = dict()

        for aggregator in g.aggregators_pool:
            thread.start_new_thread(self.one_source_processor, (aggregator, query, data_basket, data_basket_lock))

        while len(data_basket) < len(self.aggregators_pool): pass

        log.debug('Returning data from aggregator')

        return data_basket
    
    def one_source_processor(self, aggregator, book_title, basket, basket_lock):
        founded = aggregator.search_by_title(book_title)
        basket_lock.acquire()
        basket[aggregator.name] = founded
        basket_lock.release()
    
    
